package com.coco.thread.syn;

/**
 * 对象锁
 * 锁的是 同一个对象的同一个方法
 */
public class SynObject {
    private long count = 0;
    private Object obj = new Object();
    static class MyThread extends Thread{
        private SynObject test;
        MyThread(SynObject test){
            this.test =test;
        }
        @Override
        public void run() {
            for(int i=0;i<1000;i++){
                test.count();
            }
            System.out.println(Thread.currentThread().getName()+ "--- " +test.count);
        }
    }

    /**
     * 方式一
     * 在方法上添加关键词
     */
//    public synchronized void count(){
//        count++;
//    }

    /**
     * 方式二
     * 添加关键词块
     */
//    public void count(){
//        synchronized(this){
//            count++;
//        }
//    }

    /**
     *
     * 方式三
     * 锁对象的变量
     */
    public void count(){
        synchronized(obj){
            count++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SynObject test = new SynObject();
        MyThread myThread1 = new MyThread(test);
        myThread1.setName("myThread1");
        myThread1.start();

        MyThread myThread2 = new MyThread(test);
        myThread2.setName("myThread2");
        myThread2.start();

        MyThread myThread3 = new MyThread(test);
        myThread3.setName("myThread3");
        myThread3.start();

        Thread.sleep(1000);
        System.out.println(test.count);
    }

}
